package com.ai.controller.ws;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wuchen
 */
@Component
@ServerEndpoint("/websocket/{userId}")
public class WebSocket {
    private static final Logger logger = LoggerFactory.getLogger(WebSocket.class);

    /**
     * websocket连接信息
     */
    private static Map<Long, Session> sessionPool = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") Long userId) {
        try {
            sessionPool.put(userId, session);
            logger.info("【WebSocket消息】有新的连接，总数为：" + sessionPool.size());
        } catch (Exception e) {
            logger.error("【WebSocket消息】发生异常",e);
        }
    }

    @OnClose
    public void onClose(Session session) {
        try {
            sessionPool.remove(session);
            logger.info("【WebSocket消息】连接断开，总数为：" + sessionPool.size());
        } catch (Exception e) {
           logger.error("【WebSocket消息】发生异常",e);
        }
    }


}
